package com.liujit.standard.basis.core.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

import java.io.InputStream;

/**
 * @description: XSS工具类
 * @author: liujun
 * @create: 2021/3/28 5:15 下午
 **/
@Slf4j
public class XssUtil {

    public static String clearXss(String val) {
        if (StrUtil.isBlank(val)) {
            return val;
        }
        try {
            InputStream is = XssUtil.class.getResourceAsStream("/antisamy.xml");
            AntiSamy antiSamy = new AntiSamy();
            Policy policy = Policy.getInstance(is);
            return StringEscapeUtils.unescapeHtml4(antiSamy.scan(val, policy).getCleanHTML());
        } catch (PolicyException e) {
            log.error(e.getMessage());
        } catch (ScanException e) {
            log.error(e.getMessage());
        }
        return val;
    }
}
